<template>
	<image class="picture_codeqr" :src="lodRicture || picture" mode=""></image>

	<l-painter ref="painter"
		isCanvasToTempFilePath
		path-type="url"
		hidden
		@success="picture = $event"></l-painter>

	<view class="btn" @click="preserve">立即保存</view>
	<view style="height: 40rpx;"></view>
</template>

<script setup>
	import { onLoad, onReady } from '@dcloudio/uni-app'
	import { ref, reactive, watch } from 'vue';
	import api from '../../api/api';

	import { useCounterStore } from '../../stores/user';
	import { storeToRefs } from 'pinia'
	const use = useCounterStore()
	const { userinfo } = storeToRefs(use)


	const img = ref('')

	const painter = ref(null)

	let picture = ref('')
	let lodRicture = ref('')

	watch(picture, (newVal) => {
		api.setStorage('picture', newVal)
	})
	onReady(() => {
		// painter.value.render(posterStr(img.value));
	})
	onLoad(() => {
		if (api.getStorage('picture')) {
			lodRicture.value = api.getStorage('picture')
		}

		api.user.qr_code({
			path: '/pages/login/login?id=' + userinfo.value.user_id
		}).then(res => {
			img.value = 'https://' + res.data

			painter.value.render(posterStr(img.value));
		})
	})

	function posterStr(img) {
		return {
			css: {
				// 根节点若无尺寸，自动获取父级节点
				width: '750rpx',
				position: 'relative'
			},
			views: [{
					src: "/static/invite-bj.png",
					type: "image",
					css: {
						objectFit: "fill",
						width: "750rpx",
					},
				},
				{
					css: {
						position: 'absolute',
						top: 0,
						let: 0,
						display: 'flex',
						alignItems: 'center',
						flexDirection: 'column'
					},
					type: "view",
					views: [{
							css: {
								marginTop: '800rpx',
								backgroundColor: '#fff',
								borderRadius: '15rpx',
								width: "300rpx",
								height: "300rpx",
							},
							src: `${img}`,
							type: "image",
						},
						{
							css: {
								display: 'block',
								textAlign: 'center',
								color: '#000000',
								marginTop: '30rpx',
								fontSize: '36rpx'
							},
							type: "text",
							text: `ID: ${userinfo.value.user_id}`,
						}
					]
				},
			]
		}
	}

	function preserve() {
		uni.saveImageToPhotosAlbum({
			filePath: picture.value,
			success: function() {
				console.log('save success');
			}
		});
	}
</script>

<style lang="scss">
	.picture {
		width: 100vw;
		height: 100vh;
	}

	.picture_codeqr {
		width: 100vw;
		height: 100vh;
		display: block;
	}

	.btn {
		width: 686rpx;
		height: 100rpx;
		line-height: 100rpx;
		background: #F6941D;
		border-radius: 12rpx;
		text-align: center;
		color: #fff;
		margin: 50rpx auto 0;

		image {
			width: 100%;
			height: 100%;
		}
	}
</style>